package cn.codenest.springboot.mongo.dao.impl;

import cn.codenest.springboot.mongo.dao.StrategyDAO;
import cn.codenest.springboot.mongo.entity.StrategyEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;


import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@Component
public class StrategyDAOImpl implements StrategyDAO {


    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public void saveStrategy(StrategyEntity strategyEntity) {
        mongoTemplate.save(strategyEntity, StrategyEntity.COLLECTION_NAME);
    }

    @Override
    public List<StrategyEntity> queryStrategy(int start, int count, String strategyName) {
        long startSkip = (start - 1) * count;
        Criteria criteria = new Criteria();
        if (StringUtils.isEmpty(strategyName) == false) {
            Pattern pattern = Pattern.compile("^.*" + strategyName + ".*$", Pattern.CASE_INSENSITIVE);
            criteria.and("strategyName").regex(pattern);
        }
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.lookup("stgtype", "type", "_id", "typeText"),
                Aggregation.match(criteria),
                Aggregation.skip(startSkip),
                Aggregation.limit(count));
        AggregationResults results = mongoTemplate.aggregate(aggregation, StrategyEntity.COLLECTION_NAME, StrategyEntity.class);
        List<StrategyEntity> list = results.getMappedResults();
        return list;
    }
}
